package com.yonyou.brigade.third_parties.yihao.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yonyou.brigade.basic_init.model.BriChannel;
import com.yonyou.brigade.basic_init.service.IUserCenterService;
import com.yonyou.brigade.order_center.model.ThirdResult;
import com.yonyou.brigade.third_parties.yihao.constants.YihaoConstants;
import com.yonyou.brigade.third_parties.yihao.dao.YihaoDeptMapper;
import com.yonyou.brigade.third_parties.yihao.model.YihaoDept;
import com.yonyou.brigade.third_parties.yihao.service.ICLYHPublicService;
import com.yonyou.brigade.third_parties.yihao.service.IYihaoDeptService;
import com.yonyou.brigade.order_center.util.YHUtils;
import com.yonyou.ybzboot.uc.dto.UcUserDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author houyb
 * @since 2020-01-14
 */
@Service
public class YihaoDeptServiceImpl extends ServiceImpl<YihaoDeptMapper, YihaoDept> implements IYihaoDeptService {

    @Autowired
    private IUserCenterService iUserCenterService;

    @Autowired
    private ICLYHPublicService iclyhPublicService;

    @Autowired
    private YHUtils yhUtils;

    private String DeptCompareProperties = "pkDept,superDept,deptName";

    private Logger logger= LoggerFactory.getLogger(this.getClass());


    /**
     * 同步部门
     * @param tenant
     * @param phone
     * @param briChannel
     */
    @Override
    public void sysUserDept(String tenant, String phone, BriChannel briChannel){

        UcUserDto userDto = iUserCenterService.getCompleteUcUserDtoByPhone(phone, tenant);
        if (userDto == null){
            return ;
        }
        Wrapper<YihaoDept> wrapper = new EntityWrapper<>();
        wrapper.eq(YihaoDept.PKDEPT,userDto.getDeptPk());
        wrapper.eq(YihaoDept.TENANT, tenant);
        List<YihaoDept> yihaoDeptList = this.selectList(wrapper);
        YihaoDept yihaoDept = getYiHaoDept(userDto.getDeptPk(),userDto.getOrgPk() , userDto.getDeptName(), tenant);
        JSONObject config = JSONObject.parseObject(briChannel.getConfig());
        addOrEdit(yihaoDeptList, tenant, config, yihaoDept);

    }

    @Override
    public void sysOrgDept(String tenant, String org, String orgName, JSONObject config) {
        logger.info("同步一级部门");
        String companyID = config.getString("companyID");
        YihaoDept yihaoDept = new YihaoDept();
        yihaoDept.setDeptName(orgName);
        yihaoDept.setPkDept(org);
        yihaoDept.setSuperDept(companyID);
        yihaoDept.setTenant(tenant);

        Wrapper<YihaoDept> wrapper = new EntityWrapper<>();
        wrapper.eq(YihaoDept.PKDEPT, org);
        wrapper.eq(YihaoDept.TENANT, tenant);
        List<YihaoDept> yihaoDeptList = this.selectList(wrapper);
        addOrEdit(yihaoDeptList, tenant, config, yihaoDept);


    }


    @Override
    public void sysRootDept(String tenant, JSONObject config){
        logger.info("同步根部门");
        String companyID = config.getString("companyID");
        String companyName = config.getString("CompanyName");
        YihaoDept yihaoDept = new YihaoDept();
        yihaoDept.setDeptName(companyName);
        yihaoDept.setSuperDept(companyID);
        yihaoDept.setPkDept(companyID);
        yihaoDept.setTenant(tenant);
        Wrapper<YihaoDept> wrapper = new EntityWrapper<>();
        wrapper.eq(YihaoDept.PKDEPT, companyID);
        wrapper.eq(YihaoDept.TENANT, tenant);
        List<YihaoDept> yihaoDeptList = this.selectList(wrapper);
        addOrEdit(yihaoDeptList, tenant, config, yihaoDept);
    }

    /**
     * 新增或修改部门
     * @param yihaoDeptList
     * @param tenant
     * @param config
     * @param yihaoDept
     */
    private void addOrEdit(List<YihaoDept> yihaoDeptList, String tenant, JSONObject config, YihaoDept yihaoDept){
        if (yihaoDeptList.size() == 0){
            yihaoDeptList.add(yihaoDept);
            ThirdResult thirdResult = iclyhPublicService.sysDeptToClyh(yihaoDeptList, tenant, config, YihaoConstants.SYS_TYPE_ADD);
            if (thirdResult.getSuccess()){
                this.insertBatch(yihaoDeptList);
            }
        }else {
            //如果已经同步过，检查信息是否有变化，如果有变化则更新
            Map<String, String> compareMap = new HashMap<>();
            String[] compareFields = DeptCompareProperties.split(",");
            Map<String, Object> compareResult = yhUtils.compareFields(compareFields, compareMap, yihaoDeptList.get(0), yihaoDept);
            if (compareResult != null && compareResult.size() > 0) {
                //更新已经同步过的用户信息
                List<YihaoDept> list = new ArrayList<>();
                yihaoDept.setId(yihaoDeptList.get(0).getId());
                list.add(yihaoDept);
                ThirdResult thirdResult = iclyhPublicService.sysDeptToClyh(list, tenant, config, YihaoConstants.SYS_TYPE_EDIT);
                if (thirdResult.getSuccess()){
                    this.updateBatchById(list);
                }
            }
        }
    }

    /**
     * 返回一个部门对象
     * @param pkDept
     * @param superDept
     * @param pkDeptName
     * @return
     */
    private YihaoDept getYiHaoDept(String pkDept, String superDept, String pkDeptName, String tenant){
        YihaoDept yihaoDept = new YihaoDept();
        yihaoDept.setPkDept(pkDept);
        yihaoDept.setDeptName(pkDeptName);
        yihaoDept.setSuperDept(superDept);
        yihaoDept.setTenant(tenant);
        return yihaoDept;
    }


}
